package zuoYe.servelt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import zuoYe.dao.BaseDAO;
import zuoYe.entiy.roomPojo;
import zuoYe.dao.roomDao;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import zuoYe.dao.roomDao;

@WebServlet(value = "/users")
public class roomPojoServelt extends HttpServlet {
    roomDao roomDao = new roomDao();
    BaseDAO baseDAO = new BaseDAO();

    @Override

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String action = req.getParameter("action");
        switch (action) {
            case "list":
                getList(req, resp);
                break;
            case "count":
                try {
                    getCount(req, resp);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    private void getList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String page = req.getParameter("page");
        String size = req.getParameter("size");
        PrintWriter out = resp.getWriter();
        if (page == null || size == null) {
            return;
        }
        int pageInt = Integer.parseInt(page);
        int sizeInt = Integer.parseInt(size);
        int dangQian = (pageInt - 1) * 3;
        List<roomPojo> list = roomDao.getList(dangQian, sizeInt);
        Object o = JSON.toJSON(list);
        out.print(o);
        out.flush();
        out.close();
    }


    private void getCount(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        PrintWriter out = resp.getWriter();
        int count = roomDao.count();
        out.print(JSON.toJSON(count));
        out.flush();
        out.close();
    }
}
